import { useState, useEffect } from 'react'
import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import './Todo.scss'
import TodoHeader from './TodoHeader'
import TodoList from './TodoList'
import TodoFooter from './TodoFooter'

interface TodoItem {
  id: number;
  text: string;
  completed: boolean;
  date: string; // 添加日期字段
}

interface TemplateItem {
  id: number;
  text: string;
}

// 获取当前日期字符串 YYYY-MM-DD
const getCurrentDate = () => {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
};

// 存储待办事项到本地存储
const saveTodosToStorage = (todos: TodoItem[]) => {
  try {
    localStorage.setItem('todos', JSON.stringify(todos));
  } catch (error) {
    console.error('保存待办事项失败:', error);
  }
};

// 从本地存储获取待办事项
const getStoredTodos = (): TodoItem[] => {
  try {
    const storedTodos = localStorage.getItem('todos');
    return storedTodos ? JSON.parse(storedTodos) : [];
  } catch (error) {
    console.error('获取待办事项失败:', error);
    return [];
  }
};

// 存储模板到本地存储
const saveTemplatesToStorage = (templates: TemplateItem[]) => {
  try {
    localStorage.setItem('todoTemplates', JSON.stringify(templates));
  } catch (error) {
    console.error('保存模板失败:', error);
  }
};

// 从本地存储获取模板
const getStoredTemplates = (): TemplateItem[] => {
  try {
    const storedTemplates = localStorage.getItem('todoTemplates');
    return storedTemplates ? JSON.parse(storedTemplates) : [];
  } catch (error) {
    console.error('获取模板失败:', error);
    return [];
  }
};

const Todo = () => {
  // 初始化待办事项和模板
  const [todos, setTodos] = useState<TodoItem[]>(getStoredTodos());
  const [templates, setTemplates] = useState<TemplateItem[]>(getStoredTemplates());
  const [inputValue, setInputValue] = useState('');
  const [templateInputValue, setTemplateInputValue] = useState('');
  
  // 显示状态
  const [activeTab, setActiveTab] = useState<'today' | 'templates' | 'history'>('today');
  const [currentDate, setCurrentDate] = useState(getCurrentDate());
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [selectAll, setSelectAll] = useState(false);
  
  // 过滤当天的任务
  const currentDateTodos = todos.filter(todo => todo.date === currentDate);
  const completedCount = currentDateTodos.filter(todo => todo.completed).length;
  const totalCount = currentDateTodos.length;
  
  // 历史记录统计
  const uniqueDates = [...new Set(todos.map(todo => todo.date))].sort().reverse();

  // 当todos变化时，保存到localStorage
  useEffect(() => {
    saveTodosToStorage(todos);
  }, [todos]);

  // 当templates变化时，保存到localStorage
  useEffect(() => {
    saveTemplatesToStorage(templates);
  }, [templates]);

  // 添加待办事项
  const addTodo = () => {
    if (inputValue.trim()) {
      const newTodo: TodoItem = {
        id: Date.now(),
        text: inputValue,
        completed: false,
        date: currentDate
      };
      
      setTodos(prevTodos => [...prevTodos, newTodo]);
      setInputValue('');
    }
  };

  // 添加模板
  const addTemplate = () => {
    if (templateInputValue.trim()) {
      const newTemplate: TemplateItem = {
        id: Date.now(),
        text: templateInputValue
      };
      
      setTemplates(prevTemplates => [...prevTemplates, newTemplate]);
      setTemplateInputValue('');
    }
  };

  // 应用单个模板
  const applyTemplate = (template: TemplateItem) => {
    // 检查是否已存在相同任务
    const taskExists = currentDateTodos.some(todo => todo.text === template.text);
    
    if (taskExists) {
      Taro.showToast({
        title: '该任务已存在',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    const newTodo: TodoItem = {
      id: Date.now(),
      text: template.text,
      completed: false,
      date: currentDate
    };
    
    setTodos(prevTodos => [...prevTodos, newTodo]);
    
    Taro.showToast({
      title: '已添加到任务',
      icon: 'success',
      duration: 2000
    });
  };

  // 应用所有模板
  const applyAllTemplates = () => {
    if (templates.length === 0) {
      Taro.showToast({
        title: '暂无模板',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 过滤掉当天已存在的任务
    const currentTodoTexts = currentDateTodos.map(todo => todo.text);
    const newTemplates = templates.filter(template => !currentTodoTexts.includes(template.text));
    
    if (newTemplates.length === 0) {
      Taro.showToast({
        title: '所有模板任务已存在',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    const newTodos = newTemplates.map(template => ({
      id: Date.now() + Math.random() * 1000,
      text: template.text,
      completed: false,
      date: currentDate
    }));
    
    setTodos(prevTodos => [...prevTodos, ...newTodos]);
    
    Taro.showToast({
      title: `已应用${newTemplates.length}个模板`,
      icon: 'success',
      duration: 2000
    });
    
    // 应用后切换到今日任务
    setActiveTab('today');
  };

  // 删除模板
  const deleteTemplate = (id: number) => {
    setTemplates(prevTemplates => prevTemplates.filter(template => template.id !== id));
  };

  // 切换任务完成状态
  const toggleTodo = (id: number) => {
    console.log('toggleTodo', id);
    setTodos(prevTodos => 
      prevTodos.map(todo => 
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };

  // 删除待办事项
  const deleteTodo = (id: number) => {
    setTodos(prevTodos => prevTodos.filter(todo => todo.id !== id));
  };

  // 删除指定日期的所有待办事项
  const deleteAllTodosForDate = (date: string) => {
    console.log('deleteAllTodosForDate', date);
    Taro.showModal({
      title: '确认删除',
      content: `确定要删除 ${date} 的所有待办事项吗？`,
      success: function (res) {
        if (res.confirm) {
          setTodos(prevTodos => prevTodos.filter(todo => todo.date !== date));
          Taro.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  };

  // 清空已完成任务
  const clearCompletedTodos = () => {
    if (completedCount > 0) {
      setTodos(prevTodos => 
        prevTodos.filter(todo => !(todo.date === currentDate && todo.completed))
      );
    }
  };

  // 获取指定日期的统计信息
  const getDateStats = (date: string) => {
    const dateTodos = todos.filter(todo => todo.date === date);
    const completed = dateTodos.filter(todo => todo.completed).length;
    const total = dateTodos.length;
    return { 
      completed, 
      total, 
      completionRate: total > 0 ? Math.round((completed / total) * 100) : 0 
    };
  };

  // 删除当前日期的所有已选中待办事项
  const clearAllTodos = () => {
    console.log('clearAllTodos', currentDate);
    // 直接从当前的todos数组中检查已完成的任务
    const allTodos = [...todos];
    const checkedTodos = allTodos.filter(todo => todo.date === currentDate && todo.completed);
    if (checkedTodos.length === 0) {
      Taro.showToast({
        title: '没有已选中的任务',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    Taro.showModal({
      title: '确认清除',
      content: `确定要清除已选中的 ${checkedTodos.length} 个任务吗？`,
      success: function (res) {
        if (res.confirm) {
          // 仅删除当前日期的已完成任务
          setTodos(prevTodos => 
            prevTodos.filter(todo => !(todo.date === currentDate && todo.completed))
          );
          
          // 重置全选状态
          setSelectAll(false);
          
          Taro.showToast({
            title: `已清除 ${checkedTodos.length} 个任务`,
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  };

  // 全选/取消全选
  const toggleSelectAll = () => {
    if (currentDateTodos.length === 0) return;
    
    const newSelectAll = !selectAll;
    setSelectAll(newSelectAll);
    
    // 更新todos数组中当前日期的所有任务的完成状态
    setTodos(prevTodos => 
      prevTodos.map(todo => 
        todo.date === currentDate ? { ...todo, completed: newSelectAll } : todo
      )
    );
  };

  return (
    <View className='todo-container'>
      {/* 头部组件 */}
      <TodoHeader 
        activeTab={activeTab}
        setActiveTab={setActiveTab}
        currentDate={currentDate}
        setCurrentDate={setCurrentDate}
        showDatePicker={showDatePicker}
        setShowDatePicker={setShowDatePicker}
        inputValue={inputValue}
        setInputValue={setInputValue}
        templateInputValue={templateInputValue}
        setTemplateInputValue={setTemplateInputValue}
        addTodo={addTodo}
        addTemplate={addTemplate}
        applyAllTemplates={applyAllTemplates}
        uniqueDates={uniqueDates}
        getCurrentDate={getCurrentDate}
      />

      {/* 主体列表组件 */}
      <TodoList 
        activeTab={activeTab}
        currentDate={currentDate}
        currentDateTodos={currentDateTodos}
        templates={templates}
        uniqueDates={uniqueDates}
        selectAll={selectAll}
        toggleSelectAll={toggleSelectAll}
        toggleTodo={toggleTodo}
        deleteTodo={deleteTodo}
        applyTemplate={applyTemplate}
        deleteTemplate={deleteTemplate}
        deleteAllTodosForDate={deleteAllTodosForDate}
        getDateStats={getDateStats}
        setCurrentDate={setCurrentDate}
        setActiveTab={setActiveTab}
      />

      {/* 底部组件 */}
      <TodoFooter 
        activeTab={activeTab}
        totalCount={totalCount}
        completedCount={completedCount}
        clearCompletedTodos={clearCompletedTodos}
        clearAllTodos={clearAllTodos}
      />
    </View>
  );
};

export default Todo; 